<?php

require_once ('html/htmlHelper.php');
require_once ('fileIO/fileHelper.php');
require_once 'session/access.php';
require_once 'utility.php';

if (!isAuthorized("editDBSubmit.php")) {
    header("location: notAuthorized.php?page=editDBSubmit=1");
}

$request = $_POST['submit'];

//update sensors table from the given file
if (strcmp($request, "updateSensors") == 0) {
    $filename = "fileIO/sensors.csv";
    //$filename = "fileIO/Oscar_sensors_operational.csv";
    $array = readFileIntoArray($filename, ",");
    updateSensors($array);
}
//update satellites table from the given file
else if (strcmp($request, "updateSatellites") == 0) {
    $filename = "fileIO/Oscar_Satellites_operational.csv";
    //$filename = "fileIO/OscarSatellites2000_2059.csv";
    $array = readFileIntoArray($filename, ",");
    updateSatellites($array);
}
//update parameters table from the given file
else if (strcmp($request, "updateParameters") == 0) {
    $filename = "fileIO/encloseure1_parameters.csv";
    $array = readFileIntoArray($filename, "\t");
    updateParameters($array);
}
//update agencies table from the given file
else if (strcmp($request, "updateSpaceAgencies") == 0) {
    $filename = "fileIO/spaceAgencies.csv";
    $agencyArray = readFileIntoArray($filename, ",");
    populateSpaceAgencies($agencyArray);
}
//update programme
else if (strcmp($request, "updateProgramme") == 0) {
    $filename = "fileIO/Oscar_Satelliteprogrammes_operational.csv";
    $agencyArray = readFileIntoArray($filename, ",");
    populateProgrammeTable($agencyArray);
}
//update wbs table from the given file
else if (strcmp($request, "updateWbs") == 0) {
    $filename = "fileIO/wbs.txt";
    $array = readFileIntoArray($filename, "\t");
    updateWbs($array);
    printArray($array);
}
//clear the db
else if (strcmp($request, "Clear Database") == 0) {
    clearDatabase();
}
//clear projects from db
else if (strcmp($request, "Clear Projects") == 0) {
    clearProjects();
    header("location:editDB.php?editDb=1");
}
//New requirement submission
else if (strcmp($request, "Submit New Requirement") == 0) {
    if (createNewReqQuery()) {
        header("location:editDB.php?reqEdit=1&update=Requirement created successfully");
    } else {
        echo "<br>Failure<br>";
    }
}
//Requirement priority submission
else if (strcmp($request, "Submit Priority Changes") == 0) {
    if (updatePriority()) {
        header("location:editDB.php?reqEdit=1&update=Priorities updated successfully");
    } else {
        echo "<br>Failure<br>";
    }
}
//Delete a single project
else if (strcmp($request, "Delete") == 0) {
    echo "hello <br>";
    $projectId = $_POST['dropdownProject'];
    deleteProject($projectId);
}
//Update a requirement
else if (strcmp($request, "Update Requirement") == 0) {
    if (updateRequirement()) {
        header("location:editDB.php?reqEdit=1&update=Updated requirement successfully");
    } else {
        echo "<br>Failure<br>";
    }
}
//Delete a requirement
else if (strcmp($request, "Delete Requirement") == 0) {
    //print_r($_POST);
    $reqId = $_POST['reqID'];
    if (deleteRequirement($reqId)){
    header("location:editDB.php?reqEdit=1&update=Deleted requirement successfully");
    }
    else{
       echo "<br>Failure<br>"; 
    }
}
//Update a satellite
else if (strcmp($request, "Update Satellite") == 0) {
    updateSatellite();
    header("location:editDB.php?platformEdit=1");
}
//Create a sensor
else if (strcmp($request, "Create Sensor") == 0) {
    createSensor();
    header("location:editDB.php?sensorEdit=1");
}
//Update a sensor
else if (strcmp($request, "Update Sensor") == 0) {
    updateSensor();
    header("location:editDB.php?sensorEdit=1");
}
//Create a parameter
else if (strcmp($request, "Create Parameter") == 0) {
    createParameter();
    header("location:editDB.php?paramEdit=1");
}
//Update a Parameter
else if (strcmp($request, "Update Parameter") == 0) {
    updateParameter();
    header("location:editDB.php?paramEdit=1");
}
//Create a satellite
else if (strcmp($request, "Create Satellite") == 0) {
    createSatellite();
    header("location:editDB.php?platformEdit=1");
} else if (strcmp($request, "Create EDR") == 0) {
    createEDR();
    header("location:editDB.php?paramEdit=1");
}
//Update a platform programme
else if (strcmp($request, "Update Programme") == 0) {
    updateProgramme();
    header("location:editDB.php?platformEdit=1");
}
//Create a platform program
else if (strcmp($request, "Create Programme") == 0) {
    createProgramme();
    header("location:editDB.php?platformEdit=1");
}
//Create a platform agency
else if (strcmp($request, "Create Agency") == 0) {
    if (createAgency()) {
        header("location:editDB.php?platformEdit=1");
    } else {
        echo "Error <br>";
    }
} else if (strcmp($request, "Create Status") == 0) {
    if (createHardwareStatus()) {
        header("location:editDB.php?platformEdit=1");
    } else {
        echo "Error <br>";
    }
}
//Update a platform agency
else if (strcmp($request, "Update Agency") == 0) {
    if (updateAgency()) {
        header("location:editDB.php?platformEdit=1");
    } else {
        echo "Error <br>";
    }
} else if (strcmp($request, "Create Hardware Status") == 0) {
    if (createAgency()) {
        header("location:editDB.php?platformEdit=1");
    } else {
        echo "Error <br>";
    }
} else {
    //updateSensorSatAndEdr($array);
    echo "unknown type " . $request;
}

function updatePriority() {
    //echo "Update priority received <br><br>";
    //print_r($_POST);
    if (isset($_POST['hiddenList'])) {
        $stringList = $_POST['hiddenList'];
        $list = explode(",", $stringList);
        for ($i = 0; $i < sizeof($list); $i++) {
            if (strlen($list[$i]) > 0) {
                //echo "$i: $list[$i] ";
                $priority = $i + 1;
                $updateResult = executeSelect("UPDATE requirement SET priority=$priority WHERE description='$list[$i]'");
                if (!$updateResult) {
                    return false;
                }
                //echo '<br>';
            }
        }
    } else {
        return false;
    }
    return true;
}

function createNewReqQuery() {
    $reqName = $_POST['textfieldReq'];
    $reqSource = $_POST['textfieldSource'];
    $fiscalYear = $_POST['fyDropdown'];
    $parameterIdArray = array();
    for ($i = 0; $i < 40; $i++) {
        $name = 'checkbox' . $i;
        if (isset($_POST['' . $name . ''])) {
            //echo 'Checkbox ' . $i . ' was selected with value of ' . $_POST['' . $name . ''] . '<br>';
            $parameterID = $_POST['' . $name . ''];
            array_push($parameterIdArray, $parameterID);
        } else {
            //echo ' ' . $name . ' not selected <br>';
        }
    }
    return addNewReq($reqName, NULL, $reqSource, $fiscalYear);
    //addNewReq($reqName, $parameterIdArray, $reqSource, $fiscalYear);
}

function deleteRequirement($reqId) {
    //first remove all req->parameter references
    // $reqParamResult = executeSelect("DELETE FROM reqparametermap WHERE reqID=$reqId");
    // if ($reqParamResult) {
    $reqResult = executeSelect("DELETE FROM requirement WHERE reqID=$reqId");
    if (!$reqResult) {
        return false;
    }
    return true;
//    } else {
//        echo "Error removing requirement parameter relationships <br>";
//    }
}

function updateRequirement() {
    //print_r($_POST);
    //return;
    $reqId = $_POST['reqDropdown'];
    $source = $_POST['textfieldSource'];
    //$priority = $_POST['dropdownPriority'];
    $fiscalYear = $_POST['fyDropdown'];
    $description = $_POST['textfieldDescription'];
    //iterate through the checkboxes to get the parameters
    $parameters = array();
    for ($i = 0; $i < 40; $i++) {
        $name = "checkbox$i";
        if (isset($_POST['' . $name . ''])) {
            $paramID = $_POST['' . $name . ''];
            array_push($parameters, $paramID);
        }
    }

    //set active if the checkbox was selected
//    if (isset($_POST['checkboxActive'])) {
//        $active = true;
//    } else {
//        $active = false;
//    }
    //first remove all req->parameter references
    $reqParamReault = executeSelect("DELETE FROM reqparametermap WHERE reqID=$reqId");
    if ($reqParamReault) {
        //update the requirement
        if (isYearDifferent($fiscalYear, $reqId)) {
            //echo 'Year is different <br>';
            //fy changed so update the new fy priority (default)
            $priority = getDefaultPriority($fiscalYear);
            $oldFiscalYear = getFiscalYearFromReqID($reqId);
            $reqUpdate = executeUpdate("UPDATE requirement SET source='$source', fiscalYear='$fiscalYear', priority= '$priority', description='$description' WHERE reqId=$reqId");

            //update the old fy priorities
            $reqPriorityResult = executeSelect("SELECT * FROM requirement WHERE fiscalYear=$oldFiscalYear ORDER by priority ASC");
            if ($reqPriorityResult) {
                $counter = 1;
                while ($row = mysqli_fetch_array($reqPriorityResult)) {
                    $priority = $row['priority'];
                    //echo 'Checking priority <br>';
                    if ($priority != $counter) {
                        $curReqId = $row['reqID'];
                        $reqUpdate = executeUpdate("UPDATE requirement SET priority= '$counter' WHERE reqId=$curReqId");
//                        if ($reqUpdate) {
//                            echo 'Updating priority to ' . $counter . ' <br>';
//                        }
                    }
                    $counter++;
                }
            }
        } else {
            //no change in fy so no change to priority
            $reqUpdate = executeUpdate("UPDATE requirement SET source='$source', fiscalYear='$fiscalYear', description='$description' WHERE reqId=$reqId");
        }
        if ($reqUpdate) {
            //add the new req->parameter references
            for ($i = 0; $i < sizeof($parameters); $i++) {
                $paramInsertResult = executeInsert("INSERT into reqparametermap (reqID,parameterID) values ($reqId, $parameters[$i])");
            }
            //echo '<h2>Successful update</h2> <br>';
            //echo '<a href="editDB.php?reqEdit=1">Back to Add/Edit Requirements</a>';
        } else {
            //echo 'Error updating req <br>';
            return false;
            //echo "UPDATE requirement SET source='$source', priority=$priority WHERE reqId=$reqId <br>";
        }
    } else {
        //echo "error deleting old req ->param references <br>";
        return false;
    }
    return true;
}

function getCheckboxList() {
    $array = array();
    for ($i = 0; $i < 40; $i++) {
        $name = "checkbox$i";
        if (isset($_POST['' . $name . ''])) {
            $value = $_POST['' . $name . ''];
            array_push($array, $value);
        }
    }
    return $array;
}

function createHardwareStatus() {
    $status = $_POST['statusTextField'];
    $statusResult = executeInsert("INSERT into hardwarestatus (status) values ('$status')");
    if ($statusResult) {
        return true;
    } else {
        return false;
    }
}

function createEDR() {
    print_r($_POST);
    $platformID = $_POST['platformDropdown'];
    $sensorID = $_POST['sensorDropdown'];
    $parameterID = $_POST['parameterDropdown'];
    $limitation = $_POST['limitationTextField'];
    $relevanceID = $_POST['relevanceDropdown'];
    //create the edr
    $ssMapResult = executeSelect("SELECT * FROM satsensormap WHERE satelliteID=$platformID AND sensorID=$sensorID");
    $row = mysqli_fetch_array($ssMapResult);
    $satSensorMapID = $row['satSensorMapID'];
    //echo "ssm: $satSensorMapID <br>";
    $edrResult = executeInsert("INSERT into edr (parameterID, satSensorMapID) values ('$parameterID', '$satSensorMapID')");

    //create parameter measured row
    $edrID_result = executeSelect("SELECT * FROM edr WHERE satSensorMapID=$satSensorMapID && parameterID=$parameterID");
    $row1 = mysqli_fetch_array($edrID_result);
    $edrID = $row1['edrID'];
    //echo "num $edrID_result->num_rows";
    $measuredResult = executeInsert("INSERT into parameterMeasured (edrID, limitation, measuringRelevanceID) values ('$edrID', '$limitation', '$relevanceID')");
//    if($agencyResult){
//        return true;
//    }
//    else{
//        return false;
//    }
}

function createAgency() {
    //print_r($_POST);
    $acronym = $_POST['acronymTextField'];
    $fullName = $_POST['nameTextField'];
    $country = $_POST['countryTextField'];

    $agencyResult = executeInsert("INSERT into spaceAgency (acronym, name, country) values ('$acronym', '$fullName', '$country')");
    if ($agencyResult) {
        return true;
    } else {
        return false;
    }
}

function updateAgency() {
    //print_r($_POST);
    $acronym = $_POST['acronymTextField'];
    $fullName = $_POST['nameTextField'];
    $country = $_POST['countryTextField'];
    $spaceAgencyID = $_POST['spaceAgencyID'];
    $agencyResult = executeInsert("UPDATE spaceAgency SET acronym='$acronym', name='$fullName', country='$country' WHERE spaceAgencyID='$spaceAgencyID'");
    if ($agencyResult) {
        return true;
    } else {
        return false;
    }
}

function updateSensor() {
    //print_r($_POST);
    $acronym = $_POST['acronymTextField'];
    $fullName = $_POST['nameTextField'];
    $launchDate = $_POST['startTextField'];
    $eol = $_POST['eolTextField'];
    $agencyID = $_POST['agencyDropdown'];
    $sensorID = $_POST['sensorID'];

    $sensorResult = executeInsert("UPDATE sensor SET acronym='$acronym', name='$fullName', startDate='$launchDate', 
                                                     endDate='$eol', spaceAgencyID='$agencyID' WHERE sensorID='$sensorID'");
}

function createSensor() {
    //print_r($_POST);
    $acronym = $_POST['acronymTextField'];
    $fullName = $_POST['nameTextField'];
    $launchDate = $_POST['startTextField'];
    $eol = $_POST['eolTextField'];
    $agencyID = $_POST['agencyDropdown'];

    $sensorResult = executeInsert("INSERT into sensor (acronym, name, startDate, endDate, spaceAgencyID) values 
                                                  ('$acronym', '$fullName', '$launchDate', '$eol', '$agencyID')");
}

function createParameter() {
    $fullName = $_POST['parameterTextField'];
    $paramResult = executeInsert("INSERT into parameter (name) values ('$fullName')");
}

function updateParameter() {
    $fullName = $_POST['parameterTextField'];
    $parameterID = $_POST['parameterID'];
    $paramResult = executeInsert("UPDATE parameter SET name='$fullName' WHERE parameterID='$parameterID'");
}

function createSatellite() {
    //print_r($_POST);
    $acronym = $_POST['acronymTextField'];
    $fullName = $_POST['nameTextField'];
    $programmeDropdownID = $_POST['programmeDropdown'];
    $launchDate = getMysqlDateFormat($_POST['satLaunchDatepicker']); //mm/dd/yyyy comes in
    $eol = $_POST['eolTextField']; //should come in as yyyy
    $agencyList = getgenericList("agency", 100);
    $sensorIDList = getgenericList("checkbox", 500);
    $statusID = $_POST['statusDropdown'];
//    echo '<br><br>';
//    echo "ACR: $acronym <br> Name:$fullName <br> programmeID: $programmeDropdownID <br> Launch: $launchDate <br> EOL: $eol <br>";
//    echo 'Agencies';
//    printNormalArray($agencyList);
//    echo '<br>';
//    echo 'Sensors';
//    printNormalArray($sensorIDList);
    //duplicates should be taken care of through form validation
    //insert the satellite first
    $satResult = executeInsert("INSERT into satellite (acronym, name, launchDate, eol, satelliteProgrammeID, hardwareStatusID) values 
                                                  ('$acronym', '$fullName', '$launchDate', '$eol', '$programmeDropdownID', '$statusID')");

    if ($satResult) {
        //echo 'Sat write a success <br>';
    }

    //relate the programme to each space agency
    for ($i = 0; $i < sizeof($agencyList); $i++) {
        $curAgencyID = $agencyList[$i];
        $agencyResult = executeInsert("INSERT into satelliteprogrammespaceagencymap (spaceAgencyID, satelliteProgramID) values
                                                                                    ('$curAgencyID','$programmeDropdownID')");
        if ($agencyResult) {
            //echo "Sat programme-->agency $i write a success <br>";
        }
    }

    //relate the sensors to this satellite
    $satIDResult = executeSelect("SELECT satelliteID FROM satellite WHERE acronym='$acronym'");
    if ($satIDResult) {
        $row = mysqli_fetch_array($satIDResult);
        $satID = $row['satelliteID'];
        for ($i = 0; $i < sizeof($sensorIDList); $i++) {
            $curSensorID = $sensorIDList[$i];
            $satSensorResult = executeInsert("INSERT into satsensormap (sensorID, satelliteID) values ('$curSensorID','$satID')");
            if ($satSensorResult) {
                echo "Sat sat-->sensor $i write a success <br>";
            }
        }
    } else {
        echo 'error retrieving satID';
    }
}

function createProgramme() {
    $acronym = $_POST['acronymTextField'];
    $fullName = $_POST['nameTextField'];
    $launchDate = getMysqlDateFormat($_POST['satLaunchDatepicker']);
    $eol = $_POST['eolTextField'];
    //update programme table
    $programmeInsertResult = executeInsert("INSERT into satelliteprogramme (acronym, name, firstLaunch, eol)
                                                                    values('$acronym', '$fullName', '$launchDate', '$eol')");

    if ($programmeInsertResult) {
        //echo 'success';
    }
    $programmeResult = executeSelect("SELECT * FROM satelliteprogramme WHERE acronym='$acronym' AND name='$fullName'");
    if ($programmeResult) {
        $row = mysqli_fetch_array($programmeResult);
        $programmeID = $row['satelliteProgrammeID'];
    }
    $agencyList = getgenericList("checkbox", 100);
    for ($i = 0; $i < sizeof($agencyList); $i++) {
        $spaceAgencyID = $agencyList[$i];
        $programmeAgencyInsertResult = executeInsert("INSERT into satelliteprogrammespaceagencymap (spaceAgencyID, satelliteProgrammeID)
                                                                                          values ('$spaceAgencyID', '$programmeID')");
    }
}

function updateProgramme() {
    $acronym = $_POST['acronymTextField'];
    $fullName = $_POST['nameTextField'];
    $launchDate = getMysqlDateFormat($_POST['satLaunchDatepicker']);
    $eol = $_POST['eolTextField'];
    $programmeID = $_POST['satelliteProgrammeID'];
    //update programme table
    $programmeUpdateResult = executeInsert("UPDATE satelliteprogramme SET acronym='$acronym', name='$fullName', firstLaunch='$launchDate', 
                                                                    eol='$eol'WHERE satelliteProgrammeID=$programmeID");

    if ($programmeUpdateResult) {
        //echo 'success';
    }

    //delete old agencies
    $delAgenciesResult = executeInsert("DELETE FROM satelliteprogrammespaceagencymap WHERE satelliteProgrammeID=$programmeID");

    //add the new agencies
    $agencyList = getgenericList("checkbox", 100);
    for ($i = 0; $i < sizeof($agencyList); $i++) {
        $spaceAgencyID = $agencyList[$i];
        $programmeAgencyInsertResult = executeInsert("INSERT into satelliteprogrammespaceagencymap (spaceAgencyID, satelliteProgrammeID)
                                                                                          values ('$spaceAgencyID', '$programmeID')");
    }
}

function updateSatellite() {
    //print_r($_POST);
    $acronym = $_POST['acronymTextField'];
    $fullName = $_POST['nameTextField'];
    $programmeDropdownID = $_POST['programmeDropdown'];
    $launchDate = getMysqlDateFormat($_POST['satLaunchDatepicker']); //mm/dd/yyyy comes in
    $eol = $_POST['eolTextField']; //should come in as yyyy
    $agencyList = getgenericList("agency", 100);
    $sensorIDList = getgenericList("checkbox", 500);
    $statusID = $_POST['statusDropdown'];
    $satId = $_POST['satID'];

    //update satellite table first
    $satUpdateResult = executeInsert("UPDATE satellite SET acronym='$acronym', name='$fullName', satelliteProgrammeID='$programmeDropdownID',
                                                           launchDate='$launchDate', eol='$eol', hardwareStatusID='$statusID' WHERE satelliteID=$satId");

    if ($satUpdateResult) {
        //echo 'success';
    }

    //first remove all satSensorMap sensors related to this satellite
    $satSensorDeleteResult = executeSelect("DELETE FROM satsensormap WHERE satelliteID=$satId");
    if (!$satSensorDeleteResult) {
        //echo 'Could not remove any parameters if they were selected <br>';
    }
    //add the new satSensor references
    for ($i = 0; $i < sizeof($sensorIDList); $i++) {
        //see if we can query the satsensorMapID
        $satSensorQueryResult = executeInsert("SELECT satSensorMapID FROM satsensormap WHERE satelliteID=$satId AND sensorID=$sensorIDList[$i]");
        if (!$satSensorQueryResult || $satSensorQueryResult->num_rows === 0) {
            //it does not exist so insert it
            $satSensorInsertResult = executeInsert("INSERT into satsensormap (satelliteID, sensorID) values ($satId, $sensorIDList[$i])");
//            echo "Successfully added ";
//            echo getSensorName($sensorIDList[$i]);
//            echo " to ";
//            echo getSatelliteName($satId);
//            echo " <br>";
            //now query it again
            //$satSensorQueryResult = executeInsert("SELECT satSensorMapID FROM satsensormap WHERE satelliteID=$satId AND sensorID=$sensorIDList[$i]");
        }
//        $row = mysqli_fetch_array($satSensorQueryResult);
//        $ssmID = $row['satSensorMapID'];
//        $edrInsertResult = executeInsert("INSERT into edr (satelliteID, sensorID) values ($satId, $sensorIDList[$i])");
    }
    //echo '<h2>Successful update</h2> <br>';
//    echo '<a href="editDB.php?reqEdit=1">Back to Add/Edit Requirements</a>';
}

//printArray($array);
//header("location:editDB.php");
//echo "complete";
getCloseTag("body");
getCloseTag("html");
?>
